package com.rendevous.dao;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;

import com.rendevous.utils.Constants;
import com.rendevous.utils.JSONParser;
import com.rendevous.bean.Task;
import com.rendevous.exception.TaskNotExistException;

/**
 * @author see jiet 
 * modified by ykGao 
 * 
 */

public abstract class BasicDAO{
	protected String filePath;
	protected JSONParser parser;
	protected Map<Long, JSONObject> taskMap;

	public abstract boolean createTask(Task task);

	public abstract boolean updateTask(Task task);

	public abstract boolean deleteTask(long taskId);

	public abstract boolean updateFile();


	public BasicDAO() {
		parser = new JSONParser();
		taskMap = null;
	}
	
	public String getDataPath() {
		return filePath;
	}


	public List<Task> getAllTask(){
		JSONArray taskList = new JSONArray();
		taskList.addAll(taskMap.values());
		return parser.JSONArray2List(taskList);
	}
	
	public List<Task> getTaskByDate(){
		JSONArray result = new JSONArray();
		for (JSONObject task : taskMap.values()) {
			String endDate = (String) task.get(Constants.KEY_END_TIME);
		
			if (!endDate.equals("")) {
				result.add(task);
			}
		}
		return parser.JSONArray2List(result);
	}
	
	public List<Task> getTaskByKeyword(String keyword){
		JSONArray result = new JSONArray();
		for (JSONObject task : taskMap.values()) {
			String content = (String) task.get(Constants.KEY_CONTENT);

			if (content.toLowerCase().contains(keyword.toLowerCase())) {
				result.add(task);
			}
		}
		return parser.JSONArray2List(result);
	}
	
	public List<Task> getTaskByPriority(){
		JSONArray result = new JSONArray();
		for (JSONObject task : taskMap.values()) {
			String priority = (String) task.get(Constants.KEY_PRIORITY);

			if (!priority.equals("")) {
				result.add(task);
			}
		}
		return parser.JSONArray2List(result);
	}
	
	public Task getTaskById(long id) throws TaskNotExistException {
		JSONObject task = taskMap.get(id);
		if (task == null) throw new TaskNotExistException();
		else return parser.Json2Task(task);
	}

}
